package com.bzkj.basicinfo.service.exception.impl;

import com.bzkj.basicinfo.domain.exception.WmsExceptionRecordEntity;
import com.bzkj.basicinfo.mapper.exception.WmsExceptionRecordMapper;
import com.bzkj.basicinfo.service.exception.WmsExceptionRecordService;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.page.TableDataInfo;
import com.bzkj.common.utils.DateUtils;
import com.bzkj.common.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * WMS异常记录服务实现类
 *
 * @author WMS
 * @date 2025-10-23
 */
@Service
public class WmsExceptionRecordServiceImpl implements WmsExceptionRecordService {

    @Autowired
    private WmsExceptionRecordMapper exceptionRecordMapper;

    @Override
    public TableDataInfo getExceptionRecordList(WmsExceptionRecordEntity entity, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<WmsExceptionRecordEntity> list = exceptionRecordMapper.selectExceptionRecordList(entity);
        PageInfo<WmsExceptionRecordEntity> pageInfo = new PageInfo<>(list);

        TableDataInfo dataTable = new TableDataInfo();
        dataTable.setCode(200);
        dataTable.setMsg("查询成功");
        dataTable.setRows(list);
        dataTable.setTotal(pageInfo.getTotal());
        return dataTable;
    }

    @Override
    public AjaxResult getExceptionRecordDetail(Long id) {
        WmsExceptionRecordEntity record = exceptionRecordMapper.selectExceptionRecordById(id);
        if (record == null) {
            return AjaxResult.error("异常记录不存在");
        }

        Map<String, Object> result = new HashMap<>();
        result.put("record", record);
        return AjaxResult.success("查询成功", result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createExceptionRecord(String exceptionType, String relatedOrderType,
                                          String relatedOrderNo, Long relatedOrderId,
                                          String exceptionTitle, String exceptionDesc,
                                          String exceptionReason, String operator) {
        try {
            // 参数校验
            if (StringUtils.isEmpty(exceptionType)) {
                return AjaxResult.error("异常类型不能为空");
            }
            if (StringUtils.isEmpty(relatedOrderType)) {
                return AjaxResult.error("关联单据类型不能为空");
            }
            if (StringUtils.isEmpty(relatedOrderNo)) {
                return AjaxResult.error("关联单据号不能为空");
            }
            if (StringUtils.isEmpty(exceptionTitle)) {
                return AjaxResult.error("异常标题不能为空");
            }

            // 生成异常编号
            String exceptionNo = generateExceptionNo(exceptionType);

            // 创建异常记录
            WmsExceptionRecordEntity record = new WmsExceptionRecordEntity();
            record.setExceptionNo(exceptionNo);
            record.setExceptionType(exceptionType);
            record.setExceptionLevel(getExceptionLevel(exceptionType)); // 根据类型自动设置级别
            record.setRelatedOrderType(relatedOrderType);
            record.setRelatedOrderNo(relatedOrderNo);
            record.setRelatedOrderId(relatedOrderId);
            record.setExceptionTitle(exceptionTitle);
            record.setExceptionDesc(exceptionDesc);
            record.setExceptionReason(exceptionReason);
            record.setHandleStatus("pending"); // 待处理
            record.setCreateBy(operator);
            record.setCreateTime(new Date());

            int rows = exceptionRecordMapper.insertExceptionRecord(record);
            if (rows <= 0) {
                return AjaxResult.error("创建异常记录失败");
            }

            return AjaxResult.success("创建异常记录成功", exceptionNo);
        } catch (Exception e) {
            throw new RuntimeException("创建异常记录异常：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult handleException(Long id, String handlePlan, String handleResult, String handler) {
        try {
            // 查询异常记录
            WmsExceptionRecordEntity record = exceptionRecordMapper.selectExceptionRecordById(id);
            if (record == null) {
                return AjaxResult.error("异常记录不存在");
            }

            // 只有待处理或处理中状态才能处理
            if (!"pending".equals(record.getHandleStatus()) && !"processing".equals(record.getHandleStatus())) {
                return AjaxResult.error("只有待处理或处理中状态的异常才能处理");
            }

            // 更新异常记录
            record.setHandleStatus("resolved"); // 已解决
            record.setHandlePlan(handlePlan);
            record.setHandleResult(handleResult);
            record.setHandler(handler);
            record.setHandleTime(new Date());
            record.setUpdateBy(handler);
            record.setUpdateTime(new Date());

            int rows = exceptionRecordMapper.updateExceptionRecord(record);
            if (rows <= 0) {
                return AjaxResult.error("处理异常记录失败");
            }

            return AjaxResult.success("处理异常记录成功");
        } catch (Exception e) {
            throw new RuntimeException("处理异常记录异常：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult closeException(Long id, String closeReason, String operator) {
        try {
            // 查询异常记录
            WmsExceptionRecordEntity record = exceptionRecordMapper.selectExceptionRecordById(id);
            if (record == null) {
                return AjaxResult.error("异常记录不存在");
            }

            // 只有已解决状态才能关闭
            if (!"resolved".equals(record.getHandleStatus())) {
                return AjaxResult.error("只有已解决状态的异常才能关闭");
            }

            // 更新异常记录
            record.setHandleStatus("closed"); // 已关闭
            record.setCloseReason(closeReason);
            record.setCloseTime(new Date());
            record.setUpdateBy(operator);
            record.setUpdateTime(new Date());

            int rows = exceptionRecordMapper.updateExceptionRecord(record);
            if (rows <= 0) {
                return AjaxResult.error("关闭异常记录失败");
            }

            return AjaxResult.success("关闭异常记录成功");
        } catch (Exception e) {
            throw new RuntimeException("关闭异常记录异常：" + e.getMessage(), e);
        }
    }

    @Override
    public List<WmsExceptionRecordEntity> getExceptionsByRelatedOrder(String relatedOrderType, String relatedOrderNo) {
        return exceptionRecordMapper.selectByRelatedOrder(relatedOrderType, relatedOrderNo);
    }

    // ========== 私有辅助方法 ==========

    /**
     * 生成异常编号
     */
    private String generateExceptionNo(String exceptionType) {
        String prefix = "EXC";
        switch (exceptionType) {
            case "inspect_reject":
                prefix = "IRE"; // Inspect Reject Exception
                break;
            case "putaway_error":
                prefix = "PAE"; // Putaway Error Exception
                break;
            case "stock_error":
                prefix = "STE"; // Stock Error Exception
                break;
            case "system_error":
                prefix = "SYE"; // System Error Exception
                break;
        }
        return prefix + DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);
    }

    /**
     * 根据异常类型获取异常级别
     */
    private String getExceptionLevel(String exceptionType) {
        switch (exceptionType) {
            case "inspect_reject":
                return "medium"; // 验收不通过-中等级别
            case "putaway_error":
                return "high"; // 上架异常-高级别
            case "stock_error":
                return "urgent"; // 库存异常-紧急级别
            case "system_error":
                return "high"; // 系统异常-高级别
            default:
                return "low"; // 默认低级别
        }
    }
}